/**
 * wait()方法和notifyAll()方法示例
 *
 * @author fireway
 * @since 2019年 02月 15日 星期五 07:22:18 CST
 */
package concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Car {
    private boolean mWaxState = false;

    /**
     * 打蜡
     */
    public synchronized void waxed() {
        mWaxState = true;
        notifyAll();
    }

    public synchronized void waitForWaxing() throws InterruptedException {
        while(!mWaxState) {
            wait();
        }
    }

    /**
     * 抛光
     */
    public synchronized void buffed() {
        mWaxState = false;
        notifyAll();
    }

    public synchronized void waitForBuffing() throws InterruptedException {
        while(mWaxState) {
            wait();
        }
    }
}

class WaxOn implements Runnable {
    private Car mCar;

    public WaxOn(Car car) {
        mCar = car;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                System.out.println("Wax On! in " + Thread.currentThread());
                TimeUnit.MILLISECONDS.sleep(200);
                mCar.waxed();
                mCar.waitForBuffing();
            }
        } catch (InterruptedException e) {
            System.out.println("Exiting via interrupt in " + Thread.currentThread());
        }
        System.out.println("Ending Wax On task in " + Thread.currentThread());
    }
}

class WaxOff implements Runnable {
    private Car mCar;

    public WaxOff(Car car) {
        mCar = car;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                mCar.waitForWaxing();
                System.out.println("Wax Off! in " + Thread.currentThread());
                TimeUnit.MILLISECONDS.sleep(200);
                mCar.buffed();
            }
        } catch (InterruptedException e) {
            System.out.println("Exiting via interrupt in " + Thread.currentThread());
        }
        System.out.println("Ending Wax Off task in " + Thread.currentThread());
    }

}

public class WaxOMatic {
    public static void main(String[] args) {
        Car car = new Car();
        ExecutorService exec = Executors.newCachedThreadPool();
        exec.execute(new WaxOff(car));
        exec.execute(new WaxOn(car));

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        exec.shutdownNow();
    }
}
